<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="损失原因编码" prop="lossCode">
        <el-input v-model="queryParams.lossCode" placeholder="请输入损失原因编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="损失原因名称" prop="lossName">
        <el-input v-model="queryParams.lossName" placeholder="请输入损失原因名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['lamp:loss-reason:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['lamp:loss-reason:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['lamp:loss-reason:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 修改表格配置，移除expand-row-keys属性 -->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
      row-key="id"
      @expand-change="handleExpandChange"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            :data="props.row.childrenList" border
            style="width: 100%; margin-top: 10px"
          >
            <el-table-column label="损失原因编码" prop="lossCode" align="center"  />
            <el-table-column label="损失原因名称" prop="lossName" align="center"  />
            <el-table-column label="备注" prop="remark" align="center"  />
            <el-table-column label="状态" prop="status" align="center" >
              <template slot-scope="scope">
                <span>{{ scope.row.status === '1' ? '启用' : '禁用' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                           v-hasPermi="['lamp:loss-reason:update']">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['lamp:loss-reason:delete']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" />
      <el-table-column label="损失原因编码" align="center" prop="lossCode" />
      <el-table-column label="损失原因名称" align="center" prop="lossName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status === '1' ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['lamp:loss-reason:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['lamp:loss-reason:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <LossReasonForm ref="formRef" @success="getList" />
  </div>
</template>

<script>
import * as LossReasonApi from '@/api/lamp/lossreason/index.js';
import LossReasonForm from './LossReasonForm.vue';
export default {
  name: "LossReason",
  components: {
    LossReasonForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 损失原因列表
      list: [],
      // 展开的行ID数组
      // 移除expandRowKeys数组
      // expandRowKeys: [],
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        lossCode: null,
        lossName: null,
        parentId: 0, // 默认查询父级id为0的
        remark: null,
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await LossReasonApi.getLossReasonPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },

    // 处理行展开/收起
    // 修改handleExpandChange方法，使用this.$set确保响应式更新
    async handleExpandChange(row, expanded) {
      if (expanded) {
        try {
          // 加载子级列表
          const res = await LossReasonApi.getLossReasonPage({
            parentId: row.id,
            pageNo: 1,
            pageSize: 100
          });
          // 使用this.$set确保响应式更新
          this.$set(row, 'childrenList', res.data.list);
        } catch (error) {
          this.$message.error('获取子级列表失败');
        }
      } else {
        // 收起时清空子级数据
        if (row.childrenList) {
          this.$set(row, 'childrenList', null);
        }
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.parentId = 0; // 重置时恢复默认parentId=0
      this.queryParams.pageSize = 100; // 重置时恢复默认pageSize=100
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除损失原因编号为"' + id + '"的数据项?')
      try {
        await LossReasonApi.deleteLossReason(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 批量删除损失原因 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await LossReasonApi.deleteLossReasonList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有损失原因数据项?');
      try {
        this.exportLoading = true;
        const data = await LossReasonApi.exportLossReasonExcel(this.queryParams);
        this.$download.excel(data, '损失原因.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
